# login to secondlife

import sys
import xmlrpclib
import md5
import SocketServer 

URL = "https://login.aditi.lindenlab.com/cgi-bin/login.cgi" 
#URL = "https://login.agni.lindenlab.com/cgi-bin/login.cgi" 
PLATFORM=sys.platform

class PacketRequestHandler(SocketServer.DatagramRequestHandler):
    
    def handle(self):
        """handle a request"""
        print self.request
        import pdb; pdb.set_trace()

class LoginError(Exception):
    """a login error has occurred"""

class LoginFailedError(LoginError):
    """something is wrong with the login"""
    
    def __init__(self,value,msg=""):
        """initialize"""
        self.value = value
        self.msg = msg

    def __str__(self):
        """return printable version"""
        if value=="key":
            return repr(self.value)
            return repr("Password wrong: %s\n" %self.msg)
        else:
            return repr(self.value)
            return repr("Unkown login failure: %s - %s\n" %(self.value,self.msg))

class Login:

    def __init__(self,first,last,password,home="last",
        major=0,minor=0,patch=0,build=0,
        platform=PLATFORM,
        mac="00:00:00:00:00:00",
        options="",
        user_agent="pysecondlife",
        id0="",
        agree_to_tos=None,
        viewer_digest="68920a26-9f41-b742-a5e6-db6a713dcd96"):

        self.first = first
        self.last = last
        self.password = "$1$"+md5.new(password).hexdigest()
        self.home = home

        self.major = major
        self.minor = minor
        self.patch = patch
        self.build = build

        self.platform = platform
        self.mac = mac
        self.options = options
        self.user_agent = user_agent
        self.id0 = id0
        self.agree_to_tos = agree_to_tos
        self.viewer_digest = viewer_digest

    def login(self):
        """try to login to the secondlife grid"""
        server = xmlrpclib.Server(URL)
        params = {
            'first' : self.first,
            'last' : self.last,
            'passwd' : self.password,
            'start' : self.home,
            'platform' : self.platform,
            'major' : self.major,
            'minor' : self.minor,
            'patch' : self.patch,
            'build' : self.build,
        }
        try:
            login_response=server.login_to_simulator(params)
        except:
            raise LoginError, "unable to connect to server '%s'" %URL
       
        print "trying"
        success = login_response.get("login","false") == "true"
        print success
        if not success:
            reason = login_response.get("reason","unkown")
            msg = login_response.get("msg","")
            print reason,msg
            raise LoginFailedError(reason)

        # create sim and avatar objects
        sim = Simulator(**login_response)
        avatar = Avatar(**login_response)
        print login_response

        #sim.initialize()

class Simulator:
    """models a simulator"""

    def __init__(self,sim_ip=None, sim_port=None, circuit_code=None, region_x=None, region_y=None, **kwargs):
        """initialize the simulator"""
        self.sim_ip = sim_ip
        self.sim_port = sim_port
        self.circuit_code = circuit_code
        self.region_x = region_x
        self.region_y = region_y

    def initialize(self):
        """initialize sockets etc."""
        print repr(self.sim_ip)
        print repr(self.sim_port)
        import socket 
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect( (self.sim_ip, self.sim_port) )
        print "listenign"
        d = s.recv(4096)
        print d
        s.close()
        print "finished"

class Avatar:
    """models an avatar"""

    def __init__(self,first_name=None, last_name=None, agent_id=None, home=None, look_at=None, **kwargs):
        """initialize the avatar"""
        self.first_name = first_name
        self.last_name = last_name
        self.agent_id = agent_id
        self.look_at = look_at



if __name__=="__main__":
    s = Login("Some","Avatar","xsh717hbxshb!!","last",1,13,1,6,"Mac")
    s.login()
